/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.httprequest;

import cn.ac.iie.di.datadock.rdata.exchange.client.core.REFieldType;
import cn.ac.iie.di.global.GlobalParas;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import sun.misc.BASE64Encoder;

/**
 *
 * @author shipengfeng
 */
public class HttpMessage implements Runnable {

    private static Logger logger = Logger.getLogger(HttpMessage.class.getName());

    @Override
    public void run() {

        BASE64Encoder encoder = new BASE64Encoder();

        while (true) {
            try {

                HashMap map = GlobalParas.myRequestPool.poll(20, TimeUnit.MILLISECONDS);
                if (map == null) {
                    continue;
                }

                Iterator it = map.entrySet().iterator();

                int count = 0;
                String[] picContext = null;
                while (it.hasNext()) {
                    Map.Entry entry = (Map.Entry) it.next();
                    String column = (String) entry.getKey();
                    if (column.equals("ifexists")) {
                        LinkedList list = (LinkedList) (List) map.get(column);
                        String[] strs = (String[]) list.get(1);
                        picContext = new String[strs.length];
                        for (int i = 0; i < strs.length; i++) {
//                            logger.info("strs: " + Arrays.asList(strs));
                            if (strs[i].equals("") || strs[i].split("[|]").length != 4 || strs[i] == null) {
                                picContext[i] = "";
                                continue;
                            }
                            String tmpPath = strs[i].split("[|]")[1];
                            if (tmpPath.equals("")) {
                                picContext[i] = "";
                            } else {
                                count++;
                                String truePath = GlobalParas.rootPath + File.separator + tmpPath;
//                                logger.info("truePath: " + truePath);
                                byte[] data = null;
                                InputStream in = new FileInputStream(truePath);
                                data = new byte[in.available()];
                                in.read(data);
                                in.close();
                                String base64ForPic = encoder.encode(data).replaceAll("\n", "").replaceAll("\r", "");
                                picContext[i] = base64ForPic;
                            }
                        }
                    }
                }

                if (picContext == null) {
                    continue;
                }
                map.remove("ifexists");

                LinkedList picList = new LinkedList();
                picList.add(REFieldType.Strings);
                picList.add(picContext);
                map.put("file_each", picList);

                int len = map.size();
                String[] colNames = new String[len];
                REFieldType[] types = new REFieldType[len];
                Object[] lines = new Object[len];

                Iterator iterator = map.entrySet().iterator();
                int idx = 0;
                while (iterator.hasNext()) {
                    try {
                        Map.Entry entry = (Map.Entry) iterator.next();
                        String column = (String) entry.getKey();
                        LinkedList list = (LinkedList) (List) map.get(column);
                        colNames[idx] = column;
                        types[idx] = (REFieldType) list.get(0);
                        lines[idx] = list.get(1);
                        idx++;
                    } catch (Exception e) {
                        logger.error(e, e);
                    }
                }

                String MsgString = null;
                try {
                    MsgString = printSinaleColumnAndData(colNames, types, lines);
                } catch (Exception ex) {
                    logger.error(ex, ex);
                }
                while (!GlobalParas.send2MyHttpRequestPool.offer(MsgString)) {
                    Thread.sleep(500);
                    if (GlobalParas.send2MyHttpRequestPool.offer(MsgString)) {
                        break;
                    }
                }
                logger.info("pic count is " + count);
            } catch (Exception e) {
                logger.error(e, e);
            }

        }
//        if (!GlobalParas.httpMsgQueue.isEmpty()) {
//            GlobalParas.httpMsgQueue.poll();
//            logger.info("kill httpMsgQueue nums is " + GlobalParas.httpMsgQueue.size());
//        }

    }

    private String printSinaleColumnAndData(Object[] columns, Object[] types, Object[] data) {
        StringBuilder sb = new StringBuilder();
        sb.append(" {");
        for (int i = 0; i < columns.length; i++) {
            if (i > 0) {
                sb.append(",");
            }
            if (types[i].equals(REFieldType.Strings)) {
                sb.append("\"" + columns[i] + "\":[");

                String[] lines = (String[]) data[i];
                if (lines.length == 0) {
                    sb.append("]");
                } else {
                    if (lines.length == 1) {
                        sb.append("\"" + lines[0] + "\"");
                    } else {
                        sb.append("\"" + lines[0] + "\"");
                        for (int j = 1; j < lines.length; j++) {
                            sb.append(",\"" + lines[j] + "\"");
                        }
                    }
                    sb.append("]");
                }

            } else if (types[i].equals(REFieldType.Structs)) {
                sb.append("\"" + columns[i] + "\":\"[");
                Map[] structs = (Map[]) data[i];
                if (structs.length == 0) {
                    sb.append("]\"");
                } else {
                    if (structs.length == 1) {
                        sb.append(structs[0].toString());
                    } else {
                        sb.append(structs[0].toString());
                        for (int j = 1; j < structs.length; j++) {
                            sb.append("," + structs[j].toString());
                        }
                    }
                    sb.append("]\"");
                }

            } else if (types[i].equals(REFieldType.Ints) || types[i].equals(REFieldType.Longs)) {
                sb.append("\"" + columns[i] + "\":[");

                long[] tmpLongs = (long[]) data[i];
                if (tmpLongs.length == 0) {
                    sb.append("]");
                } else {
                    if (tmpLongs.length == 0) {
                        sb.append(tmpLongs[0]);
                    } else {
                        sb.append(tmpLongs[0]);
                        for (int j = 1; j < tmpLongs.length; j++) {
                            sb.append("," + tmpLongs[j]);
                        }
                    }
                    sb.append("]");
                }

            } else if (columns[i].equals("cont")) {
                BASE64Encoder encoder = new BASE64Encoder();
                String tmpCont = (String) data[i];
                String base64ForCont = encoder.encode(tmpCont.getBytes()).replaceAll("\n", "").replaceAll("\r", "");
                sb.append("\"" + columns[i] + "\":\"" + base64ForCont + "\"");
            } else if (columns[i].equals("ss")) {
                BASE64Encoder encoder = new BASE64Encoder();
                String tmpCont = (String) data[i];
                String base64ForCont = encoder.encode(tmpCont.getBytes()).replaceAll("\n", "").replaceAll("\r", "");
                sb.append("\"" + columns[i] + "\":\"" + base64ForCont + "\"");
            } else if (columns[i].equals("wx_ha")) {
                BASE64Encoder encoder = new BASE64Encoder();
                String tmpCont = (String) data[i];
                String base64ForCont = encoder.encode(tmpCont.getBytes()).replaceAll("\n", "").replaceAll("\r", "");
                sb.append("\"" + columns[i] + "\":\"" + base64ForCont + "\"");
            } else if (columns[i].equals("abstr")) {
                BASE64Encoder encoder = new BASE64Encoder();
                String tmpCont = (String) data[i];
                String base64ForCont = encoder.encode(tmpCont.getBytes()).replaceAll("\n", "").replaceAll("\r", "");
                sb.append("\"" + columns[i] + "\":\"" + base64ForCont + "\"");
            } else if (columns[i].equals("title")) {
                BASE64Encoder encoder = new BASE64Encoder();
                String tmpCont = (String) data[i];
                String base64ForCont = encoder.encode(tmpCont.getBytes()).replaceAll("\n", "").replaceAll("\r", "");
                sb.append("\"" + columns[i] + "\":\"" + base64ForCont + "\"");
            } else {
                sb.append("\"" + columns[i] + "\":\"" + data[i] + "\"");
            }
        }
        sb.append("}");
        return sb.toString();
    }
}
